<!-- src/components/SalaryTab.vue -->
<template>
  <div class="salary-tab">
    <!-- 职级选择 -->
    <div class="level-buttons">
      <el-button 
        v-for="(level, index) in levels" 
        :key="index"
        :type="currentLevelIndex === index ? 'primary' : ''" 
        size="small" 
        style="margin-right: 10px; margin-bottom: 10px;"
        @click="switchLevel(index)"
      >
        {{ level.level_name }} ({{ level.level_code }})
      </el-button>
    </div>

    <!-- 当前职级信息 -->
    <div class="job-level-info" v-if="currentLevel">
      <h3>{{ currentLevel.level_name }}工程师</h3>
      <p>职级代码：{{ currentLevel.level_code }} · 样本数：{{ currentLevel.sample_count }}</p>
    </div>

    <!-- 年薪统计 -->
    <div class="salary-stats" v-if="currentLevel">
      <div class="stat-item">
        <div class="label">最低年薪</div>
        <div class="value">¥{{ formatNumber(currentLevel.min_salary) }}</div>
      </div>
      <div class="stat-item">
        <div class="label">最高年薪</div>
        <div class="value">¥{{ formatNumber(currentLevel.max_salary) }}</div>
      </div>
      <div class="stat-item">
        <div class="label">平均年薪</div>
        <div class="value">¥{{ formatNumber(currentLevel.avg_salary) }}</div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container" v-if="currentLevel">
      <div class="chart-item">
        <h4>薪资构成</h4>
        <div ref="salaryChart" class="echart"></div>
      </div>
      <div class="chart-item">
        <h4>工作经验分布</h4>
        <div ref="experienceChart" class="echart"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, watch, computed, nextTick } from 'vue';
import { CampatydataApi } from '@/utils/api';

const props = defineProps({
  companyData: {
    type: Object,
    required: true
  },
  companyId: {
    type: String,
    required: true
  }
});

const salaryChart = ref(null);
const experienceChart = ref(null);
const currentLevelIndex = ref(0);

// 计算属性：获取所有职级
const levels = computed(() => {
  return props.companyData.levels || [];
});

// 计算属性：获取当前选中的职级
const currentLevel = computed(() => {
  return levels.value.length > 0 ? levels.value[currentLevelIndex.value] : null;
});

// 格式化数字显示
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万';
  }
  return num.toLocaleString();
};

// 切换职级
const switchLevel = (index) => {
  currentLevelIndex.value = index;
};

// 初始化薪资构成柱状图
const initSalaryChart = () => {
  const chartDom = salaryChart.value;
  if (!chartDom || !currentLevel.value) return;

  // 销毁之前的图表实例
  if (salaryChartInstance) {
    salaryChartInstance.dispose();
  }

  const baseMonthly = currentLevel.value.base_monthly_comp_stats;
  const bonus = currentLevel.value.bonus_comp_stats;
  const stock = currentLevel.value.stock_comp_stats;

  const maxValue = Math.max(
    baseMonthly.max || 0,
    bonus.max || 0,
    stock.max || 0
  ) * 1.2;

  salaryChartInstance = echarts.init(chartDom);
  const option = {
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    legend: { data: ['最低', '最高', '平均'], bottom: 0 },
    grid: { left: '10%', right: '10%', bottom: '20%' },
    xAxis: {
      type: 'category',
      data: ['月基本工资', '奖金', '股票激励'],
      axisLabel: { color: '#666' }
    },
    yAxis: {
      type: 'value',
      max: maxValue > 0 ? maxValue : 200000,
      axisLabel: { 
        formatter: (value) => {
          if (value >= 10000) {
            return `${value / 10000}万`;
          }
          return value;
        } 
      }
    },
    series: [
      { 
        name: '最低', 
        type: 'bar', 
        data: [
          baseMonthly.min || 0,
          bonus.min || 0,
          stock.min || 0
        ], 
        itemStyle: { color: '#4a90e2' } 
      },
      { 
        name: '最高', 
        type: 'bar', 
        data: [
          baseMonthly.max || 0,
          bonus.max || 0,
          stock.max || 0
        ], 
        itemStyle: { color: '#7ed36f' } 
      },
      { 
        name: '平均', 
        type: 'bar', 
        data: [
          Math.round(baseMonthly.avg) || 0,
          Math.round(bonus.avg) || 0,
          Math.round(stock.avg) || 0
        ], 
        itemStyle: { color: '#f9c80e' } 
      }
    ]
  };
  salaryChartInstance.setOption(option);
};

// 初始化工作经验分布饼图
const initExperienceChart = () => {
  const chartDom = experienceChart.value;
  if (!chartDom || !currentLevel.value) return;

  // 销毁之前的图表实例
  if (experienceChartInstance) {
    experienceChartInstance.dispose();
  }

  const expDist = currentLevel.value.experience_distribution;
  const rawData = [
    { value: (expDist['0-2年'] * 100).toFixed(2), name: '0-2年' },
    { value: (expDist['3-5年'] * 100).toFixed(2), name: '3-5年' },
    { value: (expDist['6-10年'] * 100).toFixed(2), name: '6-10年' },
    { value: (expDist['10年以上'] * 100).toFixed(2), name: '10年以上' }
  ];

  // 过滤掉0值数据
  const data = rawData.filter(item => parseFloat(item.value) > 0);

  experienceChartInstance = echarts.init(chartDom);
  const option = {
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c}%' },
    series: [
      {
        name: '工作经验分布',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold',
            formatter: '{b}\n{d}%'
          }
        },
        labelLine: { show: false },
        data: data,
        itemStyle: {
          borderRadius: 10
        },
        color: ['#4a90e2', '#7ed36f', '#f9c80e', '#ff6b6b']
      }
    ]
  };
  experienceChartInstance.setOption(option);
};

let salaryChartInstance = null;
let experienceChartInstance = null;

// 监听当前职级变化，重新渲染图表
watch(currentLevel, () => {
  nextTick(() => {
    initSalaryChart();
    initExperienceChart();
  });
});

onMounted(() => {
  nextTick(() => {
    initSalaryChart();
    initExperienceChart();
  });
});
</script>

<style scoped>
.salary-tab {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.level-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.job-level-info {
  margin-bottom: 20px;
}

.job-level-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #333;
}

.job-level-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.salary-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.stat-item {
  flex: 1;
  min-width: 200px;
  text-align: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-item .label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stat-item .value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.charts-container {
  display: flex;
  gap: 30px;
}

.chart-item {
  flex: 1;
  min-width: 300px;
}

.chart-item h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.echart {
  width: 100%;
  height: 300px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .charts-container {
    flex-direction: column;
  }
  
  .chart-item {
    min-width: auto;
  }
  
  .salary-stats {
    flex-direction: column;
  }
  
  .stat-item {
    min-width: 100%;
  }
}
</style>